package com.niit.blog.controller;

import com.niit.blog.entity.domain.User;
import com.niit.blog.service.*;
import com.niit.blog.util.JwtUtils;
import com.niit.blog.util.MyResult;
import com.niit.blog.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Resource
	private BlogService blogService;
	@Resource
	private CategoryService categoryService;
	@Resource
	private LinkService linkService;
	@Resource
	private TagService tagService;

//
//	/**
//	 * @Description: 管理员首页
//	 * @Author: NIIT
//	 * @CreateTime: 2022-06-02 10:13:26
//	 * @param request
//	 * @return String
//	 */
//	@GetMapping({ "", "/", "/index", "/index.html" })
//	public String index(HttpServletRequest request) {
//		request.setAttribute("path", "index");
//
//		/** 总文章数 */
//		request.setAttribute("blogCount", blogService.getTotalBlogs());
//
//		/** 总评论数 */
//		request.setAttribute("commentCount", commentService.getTotalComments());
//
//		/** 分类数量 */
//		request.setAttribute("categoryCount", categoryService.getTotalCategories());
//
//		/** 总标签数 */
//		request.setAttribute("tagCount", tagService.getTotalTags());
//
//		/** 友情链接 */
//		request.setAttribute("linkCount", linkService.getTotalLinks());
//
//		return "user/index";
//	}

	/**
	 *
	 * @param user
	 * @return
	 */
	@PostMapping("/login")
	public Result login(@RequestBody User user){
		log.info("员工登录：{}",user);
		User u = userService.login(user);

		//登录成功，生成令牌，下发令牌
		if (u != null){
			Map<String, Object> claims = new HashMap<>();
			claims.put("userId",u.getUserId());
			claims.put("userName",u.getUserName());
			String token = JwtUtils.generateJwt(claims);
			return Result.success(token);
		}
		return Result.error("用户名或密码错误");
	}

	@GetMapping("/info")
	public MyResult<?> getUserInfo(@RequestParam("token") String token){
		Map<String,Object> data = userService.getUserInfo(token);
		log.info(token);
		if(data != null){
			return MyResult.success(data);
		}
		return MyResult.fail(20003,"用户信息获取失败");
	}

	/**
	 * @Description: 退出登录
	 * @Author: NIIT
	 * @CreateTime: 2022-5-31 10:58
	 * @param: request
	 * @return: java.lang.String
	 **/
	@GetMapping("/logout")
	public String logout(HttpServletRequest request) {
		/* 退出登录之后我们需要清除Session中的用户信息 */
		request.getSession().removeAttribute("loginUserId");
		request.getSession().removeAttribute("loginUser");
		request.getSession().removeAttribute("errorMsg");
		return "user/login";
	}

	/**
	 * @Description: 基本信息的修改和修改密码
	 * @Author: NIIT
	 * @CreateTime: 2022-5-31 11:19
	 * @param: request
	 * @return: java.lang.String
	 **/
	@GetMapping("/profile")
	public String profile(HttpServletRequest request) {
		/* 获取当前登录信息 */
		Integer loginUserId = (int) request.getSession().getAttribute("userId");
		User user = userService.getUserDetailById(loginUserId);
		/* 如果为空，则返回登录页面 */
		if (user == null) {
			return "user/login";
		}
		request.setAttribute("path", "profile");
		/* 如果不为空，则获取当前登录用户的姓名和昵称 */
		request.setAttribute("userName", user.getUserName());
		request.setAttribute("nickName", user.getNickName());
		return null;
	}

	/**
	 * @Description: 修改密码
	 * @Author: NIIT
	 * @CreateTime: 2022-5-31 14:43
	 * @param: request
	 * @param: originalPassword
	 * @param: newPassword
	 * @return: java.lang.String
	 **/
	@PostMapping("/profile/password")
	@ResponseBody
	public String passwordUpdate(HttpServletRequest request, @RequestParam("originalPassword") String originalPassword,
			@RequestParam("newPassword") String newPassword) {
		/* 判断参数（旧密码和新密码）是否为空 */
		if (StringUtils.isEmpty(originalPassword) || StringUtils.isEmpty(newPassword)) {
			return "参数不能为空";
		}
		/* 判断如果参数不为空，则是从数据库拿取用户的信息 */
		Integer loginUserId = (int) request.getSession().getAttribute("userId");
		if (userService.updatePassword(loginUserId, originalPassword, newPassword)) {
			/* 修改成功后清空session中的数据，前端控制跳转至登录页 */
			request.getSession().removeAttribute("userId");
			request.getSession().removeAttribute("user");
			request.getSession().removeAttribute("errorMsg");
			return "success";
		} else {
			return "修改失败";
		}
	}

	/**
	 * @Description: 修改个人基本信息
	 * @Author: NIIT
	 * @CreateTime: 2022-5-31 11:20
	 * @param: request
	 * @param: loginUserName
	 * @param: nickName
	 * @return: java.lang.String
	 **/
	@PostMapping("/profile/name")
	@ResponseBody
	public String nameUpdate(HttpServletRequest request, @RequestParam("userName") String userName,
			@RequestParam("nickName") String nickName) {
		/* 判断参数是否为空 */
		if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(nickName)) {
			return "参数不能为空";
		}
		/* 获取当前登录用户的id，然后根据id查询信息并修改 */
		Integer loginUserId = (int) request.getSession().getAttribute("userId");
		if (userService.updateName(loginUserId, userName, nickName)) {
			return "success";
		} else {
			return "修改失败";
		}
	}
}
